package com.woshua.gifmodel.core;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.os.Handler;
import android.widget.ImageView;

import java.io.InputStream;

public class GifDrawer {
    private InputStream inputStream;

    private ImageView imageView;

    private Movie movie;

    private Bitmap bitmap;

    private Handler handler=new Handler();

    private static final int frameDuration=16;

    private Runnable runnable=new Runnable() {
        @Override
        public void run() {
           draw();

           handler.postDelayed(runnable,frameDuration);
        }
    };

    private void draw()
    {
        canvas.save();
        movie.draw(canvas,0,0);
        canvas.restore();

        movie.setTime((int) (System.currentTimeMillis()%movie.duration()));
        imageView.setImageBitmap(bitmap);
    }
    private Canvas canvas;

    public void into(ImageView imageView)
    {
        this.imageView=imageView;

        if(inputStream==null)
        {
            return;
        }
        else if(imageView==null)
        {
            throw new RuntimeException("imageView can not is NULL");
        }
        else
        {
            movie=Movie.decodeStream(inputStream);
            if(movie==null)
            {
                throw new IllegalArgumentException("legal gif file");
            }

            if(movie.width()<=0 || movie.height()<=0)
            {
                return;
            }

            //需要空的bitmap获取canvas
            bitmap=Bitmap.createBitmap(movie.width(),movie.height(), Bitmap.Config.ARGB_8888);

            canvas = new Canvas(bitmap);
            //canvas绘制到imageView中
            handler.post(runnable);
        }
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }
}
